BUILD:=./build
SRC:=./src
INCLUDE:=-I$(SRC)/include

ENTRYPOINT:=0x10000

CFLAGS:= -m32
CFLAGS+= -fno-builtin
CFLAGS+= -nostdinc
CFLAGS+= -fno-pic
CFLAGS+= -nostdlib
CFLAGS+= -ffreestanding
CFLAGS+= -nostartfiles
CFLAGS:=$(strip ${CFLAGS})
DEBUG:= -g

$(BUILD)/boot/%.bin: $(SRC)/boot/%.asm
	$(shell mkdir -p $(dir $@))
	nasm -f bin $< -o $@
$(BUILD)/%.obj: $(SRC)/%.asm
	$(shell mkdir -p $(dir $@))
	nasm -f win32 $< -o $@
$(BUILD)/%.obj: $(SRC)/%.c
	$(shell mkdir -p $(dir $@))
	i686-w64-mingw32-gcc $(DEBUG) $(CFLAGS) $(INCLUDE) -c $< -o $@
$(BUILD)/kernel.bin: $(BUILD)/kernel/start.obj \
						$(BUILD)/main.obj \
						$(BUILD)/kernel/io.obj \
						$(BUILD)/lib/string.obj \
						$(BUILD)/lib/stdlib.obj \
						$(BUILD)/lib/bitmap.obj \
						$(BUILD)/lib/syscall.obj \
						$(BUILD)/lib/list.obj \
						$(BUILD)/lib/fifo.obj \
						$(BUILD)/kernel/console.obj \
						$(BUILD)/kernel/printk.obj \
						$(BUILD)/kernel/vsprintf.obj \
						$(BUILD)/kernel/debug.obj \
						$(BUILD)/kernel/global.obj \
						$(BUILD)/kernel/schedule.obj \
						$(BUILD)/kernel/interrupt.obj \
						$(BUILD)/kernel/handler.obj \
						$(BUILD)/kernel/clock.obj \
						$(BUILD)/kernel/time.obj \
						$(BUILD)/kernel/rtc.obj \
						$(BUILD)/kernel/memory.obj \
						$(BUILD)/kernel/assert.obj \
						$(BUILD)/kernel/gate.obj \
						$(BUILD)/kernel/thread.obj \
						$(BUILD)/kernel/mutex.obj \
						$(BUILD)/kernel/keyboard.obj \
						$(BUILD)/kernel/printf.obj \
						$(BUILD)/kernel/arena.obj \
						$(BUILD)/kernel/task.obj \
						$(BUILD)/kernel/ide.obj \
						$(BUILD)/kernel/device.obj \
						$(BUILD)/kernel/buffer.obj \
						$(BUILD)/fs/super.obj \
						$(BUILD)/fs/bmap.obj
	$(shell mkdir -p $(dir $@))
	i686-w64-mingw32-ld -m i386pe -static $^ -o $@ -Ttext $(ENTRYPOINT)
$(BUILD)/system.bin: $(BUILD)/kernel.bin
	i686-w64-mingw32-objcopy -O binary $< $@
$(BUILD)/system.map: $(BUILD)/kernel.bin
	i686-w64-mingw32-nm $< | sort > $@

.PHONY: build
build: clean $(BUILD)/boot/boot.bin $(BUILD)/boot/loader.bin $(BUILD)/system.bin $(BUILD)/system.map
	dd if=$(BUILD)/boot/boot.bin of=master.img bs=512 count=1
	dd if=$(BUILD)/boot/loader.bin of=master.img bs=512 count=4 seek=2
	dd if=$(BUILD)/system.bin of=master.img bs=512 count=200 seek=10

.PHONY: disk
disk:
	bash disk.sh

.PHONY: clean
clean:
	rm -rf $(BUILD)

.PHONY: bochsdbg
bochs: build
	bochsdbg -q -f bochs/bochsrc.bxrc